<template>
  <div class="AddOrUpdate_main add_container showDetail column_three">
    <div class="main_main">
      <el-form ref="form" :model="formData" :rules="rules" :inline="true">
        <el-form-item label="物料编码" prop="materialCode">
          <div v-if="formData.materialCode" class="show">{{ formData.materialCode }}</div>
          <div v-else class="show noData">暂无</div>
        </el-form-item>
        <el-form-item label="物料名称" prop="materialName">
          <div v-if="formData.materialName" class="show">{{ formData.materialName }}</div>
          <div v-else class="show noData">暂无</div>
        </el-form-item>
        <el-form-item label="规格型号" prop="materialModel">
          <div v-if="formData.materialModel" class="show">{{ formData.materialModel }}</div>
          <div v-else class="show noData">暂无</div>
        </el-form-item>
        <el-form-item label="物料分类" prop="materialTypeName">
          <div v-if="formData.materialTypeName" class="show">{{ formData.materialTypeName }}</div>
          <div v-else class="show noData">暂无</div>
        </el-form-item>
        <el-form-item label="物料单位" prop="materialUnitName">
          <div v-if="formData.materialUnitName" class="show">{{ formData.materialUnitName }}</div>
          <div v-else class="show noData">暂无</div>
        </el-form-item>
        <el-form-item label="备注" class="double">
          <div v-if="formData.remark" class="shows">{{ formData.remark }}</div>
          <div v-else class="show noData">暂无</div>
        </el-form-item>
      </el-form>
      <div v-if="formData.materialCode" class="processRequirement_bottom">
        <div class="processRequirement_bottom_tree">
          <div class="tree_header">外协工序</div>
          <div class="tree_container">
            <a
              v-for="(item,index) in processFlowList"
              :key="index"
              class="tree_container_item"
              :class="index==currentProcessIndex?'selected_row':''"
            >

              <div style="width:calc(100% - 70px)" @click="processClick(item,index)">{{ item.engineeringProcessName }}</div>
              <!-- <div><i style="font-size:20px;color:red;width:30px" class="el-icon-remove" @click="deleteRow(item,index)" /></div> -->
            </a>
          </div>
          <!-- <div class="addWorkProcedure" @click="addWorkProcedures">添加工序</div> -->
        </div>
        <div class="processRequirement_bottom_detail">
          <div class="formItem_header">
            {{ currentProcess.engineeringProcessName }}
          </div>
          <div class="formItem_header formItem_header_padding">
            外协原料
            <div class="formItem_header_operate">
              <!-- <a class="formItem_header_operate_item" @click="chooseMaterial2(1)">
                <svg-icon icon-class="新增" />
                <div class="item_name">添加</div>
              </a>
              <a class="formItem_header_operate_item delete" @click="deleteProduceIn">
                <svg-icon icon-class="删除" />
                <div class="item_name">删除</div>
              </a> -->
            </div>
          </div>
          <div ref="table_container" class="table_container">
            <el-table
              ref="table"
              :data="tableData1"
              stripe
              border
            >
              <el-table-column label="物料编码" prop="materialCode" :show-overflow-tooltip="true" />
              <el-table-column label="物料名称" prop="materialName" :show-overflow-tooltip="true" />
              <el-table-column label="规格型号" prop="materialModel" :show-overflow-tooltip="true" />
              <el-table-column label="物料分类" prop="materialTypeName" />
              <el-table-column label="物料单位" prop="materialUnitName" />
              <el-table-column label="需求数量" prop="needNumber" />
            </el-table>
          </div>

          <div class="formItem_header formItem_header_padding">
            外协回料
            <div class="formItem_header_operate">
              <!-- <a class="formItem_header_operate_item" @click="chooseMaterial2(2)">
                <svg-icon icon-class="新增" />
                <div class="item_name">添加</div>
              </a>
              <a class="formItem_header_operate_item delete" @click="deleteProduceOut">
                <svg-icon icon-class="删除" />
                <div class="item_name">删除</div>
              </a> -->
            </div>
          </div>

          <div ref="table_container" class="table_container">
            <el-table
              ref="table2"
              :data="tableData2"
              stripe
              border
            >
              <el-table-column label="物料编码" prop="materialCode" :show-overflow-tooltip="true" />
              <el-table-column label="物料名称" prop="materialName" :show-overflow-tooltip="true" />
              <el-table-column label="规格型号" prop="materialModel" :show-overflow-tooltip="true" />
              <el-table-column label="物料分类" prop="materialTypeName" />
              <el-table-column label="物料单位" prop="materialUnitName" />
              <el-table-column label="产出数量" prop="produceNumber" />
            </el-table>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { addOrUpdate, getInfo, getProcessInfoByMaterialId } from '@/api/outsourceManage/outsourceMaterialManagement'
import { getAllPictureCode } from '@/api/engineeringManage/documentManage'
import { getInfo as getProcessList } from '@/api/engineeringManage/processFlow'
import ChooseMaterial from './chooseMaterial.vue'
import ChooseMaterial2 from './chooseMaterial2.vue'
import ChooseBOMMaterialDetail from '@/views/engineeringManage/BOMManage/chooseBOMMaterialDetail'
import addWorkProcedure from './addWorkProcedure.vue'
export default {
  name: 'AddOrUpdate',
  props: {
    layerid: {},
    id: {},
    defaultValue: {}
  },
  data() {
    return {
      formData: {
        id: undefined,
        materialId: undefined,
        materialCode: undefined,
        materialName: undefined,
        materialModel: undefined,
        materialTypeName: undefined,
        materialUnitName: undefined,
        remark: undefined
      },
      rules: {
      },
      processFlowList: [], // 左边工艺流程列表数据

      detailForm: {}, // 计时，计件数据
      detailFormTemplate: { // 计时，计件数据的模板（初始化的时候用）
        flowDetailId: '',
        standardWorkTime: '',
        workTimePrice: '',
        unitPriceOfPiecework: ''
      },
      tableData1: [], // 生产输入数据
      tableData2: [], // 生产输出数据
      tableData3: [], // 生产输出数据

      selectionsAll1: [], // 生产输入选中值
      selectionsAll2: [], // 生产输出选中值
      selectionsAll3: [], // 生产输出选中值

      currentProcess: {}, // 左边当前选中工序
      currentProcessIndex: '', // 左边当前选中工序序号
      currentChooseType: '', // 当前选择物料的类型（生产输入/生产输出），目的是共用同一个物料选择弹框

      pictureOptions: [], // 图号下拉数据

      triggerTag: false // 触发标志，watch是否触发
    }
  },
  // watch: {
  //   'formData.flowId'(data) {
  //     if (this.triggerTag && data) {
  //       // 通过工艺流程ID，获取工艺流程明细
  //       getProcessList(data).then(res => {
  //         if (res.data.data.length > 0) {
  //           const cacheData = res.data.data
  //           cacheData.forEach(item => {
  //             item.processFlowDetailId = item.id
  //             item.flowDetailId = item.id
  //             delete item['id']
  //           })
  //           this.processFlowList = cacheData

  //           this.$nextTick(() => {
  //             this.initProcessFlowData()
  //           })
  //         } else {
  //           this.$message({
  //             message: '工艺流程数据不存在',
  //             type: 'warning'
  //           })
  //         }
  //       })
  //     }
  //   }
  // },
  mounted() {
    if (!this.id) { // 没有id就是新增
    } else { // 有id就是编辑
      this.getInfo()
    }
  },
  methods: {
    addWorkProcedures() {
      this.$layer.iframe({
        // 弹框
        content: {
          content: addWorkProcedure, // 传递的组件对象
          parent: this, // 当前的vue对象
          data: {
            selectedRow: this.tableData1 || [],
            bomId: this.formData.bomDetailId
          } // 当前主物料和当前点击的父级物料不能勾选
        },
        area: ['1000px', '650px'],
        title: '选择工序', // 标题
        shadeClose: false // 点击遮罩是否关闭
      })
    },
    getPictureOptions() {
      getAllPictureCode({ materialId: this.formData.materialId }).then(res => {
        this.pictureOptions = res.data
      })
    },
    checkCurrentForm() { // 校验当前工序的表单
      let res = true
      if (res && (this.tableData1.length > 0)) {
        const reg = /(^[1-9](\d+)?(\.\d{1,2})?$)|(^\d\.\d{1,2}$)/
        this.tableData1.forEach(item => {
          if (res && !item.needNumber) {
            this.$message({
              message: '需求数量不能为空',
              type: 'warning'
            })
            res = false
          }
          if (res && !reg.test(item.needNumber)) {
            this.$message({
              message: '需求数量最多两位小数',
              type: 'warning'
            })
            res = false
          }
        })
      }
      if (res && (this.tableData2.length > 0)) {
        const reg = /(^[1-9](\d+)?(\.\d{1,2})?$)|(^\d\.\d{1,2}$)/
        this.tableData2.forEach(item => {
          if (res && !item.produceNumber) {
            this.$message({
              message: '产出数量不能为空',
              type: 'warning'
            })
            res = false
          }
          if (res && !reg.test(item.produceNumber)) {
            this.$message({
              message: '产出数量最多两位小数',
              type: 'warning'
            })
            res = false
          }
        })
      }

      if (res) {
        return true
      } else {
        return false
      }
    },
    processClick(data, index) {
      if (this.checkCurrentForm()) {
        // 如果校验通过，先把旧数据更新到左边工序列表中
        this.processFlowList[this.currentProcessIndex]['rawMaterialList'] = this.$deepClone(this.tableData1)
        this.processFlowList[this.currentProcessIndex]['returnMaterialList'] = this.$deepClone(this.tableData2)

        this.currentProcess = data
        this.currentProcessIndex = index
        // this.detailForm.flowDetailId = data.flowDetailId
        this.tableData1 = data.rawMaterialList || []
        this.tableData2 = data.returnMaterialList || []
      }
    },
    deleteRow(item, index) {
      this.processFlowList.splice(this.processFlowList.indexOf(item), 1)
      if (this.processFlowList.length == 0) {
        this.tableData1 = []
        this.tableData2 = []
        this.currentProcess = {}
      } else {
        if (index == this.currentProcessIndex) {
          this.tableData1 = this.processFlowList[index - 1].rawMaterialList
          this.tableData2 = this.processFlowList[index - 1].returnMaterialList
          this.currentProcess = this.processFlowList[index - 1]
          this.currentProcessIndex = index - 1
        }
      }
    },
    chooseProduceIn() {
      this.currentChooseType = '生产输入'
      this.$layer.iframe({
        // 弹框
        content: {
          content: ChooseBOMMaterialDetail, // 传递的组件对象
          parent: this, // 当前的vue对象
          data: {
            selectedRow: this.tableData1 || [],
            bomId: this.formData.bomDetailId
          } // 当前主物料和当前点击的父级物料不能勾选
        },
        area: ['1000px', '650px'],
        title: '选择物料', // 标题
        shadeClose: false // 点击遮罩是否关闭
      })
    },
    chooseWorkProcedureCallBack(data) {
      data.engineeringProcessName = data.name
      data.processId = data.id
      data['returnMaterialList'] = []
      data['rawMaterialList'] = []
      console.log(data)
      this.processFlowList.push(data)
      if (this.processFlowList.length == 1) {
        this.currentProcess = this.processFlowList[0]
        this.currentProcessIndex = 0
      }
    },
    chooseBOMMaterialDetailCallBack(rowList) {
      if (!rowList) {
        return
      }
      if (this.currentChooseType == '生产输入') {
        const cacheTableData = this.$deepClone(this.tableData1)
        rowList.forEach(item => {
          if (!this.tableData1.some(item2 => item2.materialId == item.materialId)) {
            const cacheData = this.$deepClone(item)
            delete cacheData['id']
            cacheData.demandNumber = ''
            cacheTableData.push(cacheData)
          }
        })
        this.tableData1 = cacheTableData
      }
      if (this.currentChooseType == '生产输出') {
        const cacheTableData = this.$deepClone(this.tableData2)
        rowList.forEach(item => {
          if (!this.tableData2.some(item2 => item2.materialId == item.materialId)) {
            const cacheData = this.$deepClone(item)
            delete cacheData['id']
            cacheData.outputNumber = ''
            cacheTableData.push(cacheData)
          }
        })
        this.tableData2 = cacheTableData
      }
    },
    deleteProduceIn() {
      this.selectionsAll1.forEach(item => {
        this.tableData1.splice(this.tableData1.indexOf(item), 1)
      })
    },
    chooseProduceOut() {
      if (!this.formData.bomDetailId) {
        this.$message({
          message: '请先选择物料',
          type: 'warning'
        })
      } else {
        this.currentChooseType = '生产输出'
        this.$layer.iframe({
          // 弹框
          content: {
            content: ChooseBOMMaterialDetail, // 传递的组件对象
            parent: this, // 当前的vue对象
            data: {
              selectedRow: this.tableData2 || [],
              bomId: this.formData.bomDetailId
            } // 当前主物料和当前点击的父级物料不能勾选
          },
          area: ['1000px', '650px'],
          title: '选择物料', // 标题
          shadeClose: false // 点击遮罩是否关闭
        })
      }
    },
    deleteProduceOut() {
      this.selectionsAll2.forEach(item => {
        this.tableData2.splice(this.tableData2.indexOf(item), 1)
      })
    },
    chooseProduceProcess() {
      const row = {
        operationDescription: '',
        productCharacter: '',
        courseCharacter: '',
        pictureId: '',
        pictureCode: ''
      }
      this.tableData3.push(row)
    },
    deleteProduceProcess() {
      this.selectionsAll3.forEach(item => {
        this.tableData3.splice(this.tableData3.indexOf(item), 1)
      })
    },
    selectionChange1(row) {
      this.selectionsAll1 = row
    },
    selectionChange2(row) {
      this.selectionsAll2 = row
    },
    selectionChange3(row) {
      this.selectionsAll3 = row
    },
    getInfo() {
      getInfo(this.id).then(res => {
        Object.keys(this.formData).forEach(key => { // 给右边数据赋值
          this.formData[key] = res.data[key]
        })
        if (res.data.materialCode) {
          const cacheTableData = this.$deepClone(res.data.processList)
          this.processFlowList = cacheTableData
        }
        this.currentProcess = this.processFlowList[0]
        this.currentProcessIndex = 0
        console.log(11111, this.currentProcess)
        this.tableData1 = this.currentProcess.rawMaterialList || []
        this.tableData2 = this.currentProcess.returnMaterialList || []
      })
    },
    onSubmit() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.checkCurrentForm()) {
            // 如果校验通过，先把旧数据更新到左边工序列表中
            this.processFlowList[this.currentProcessIndex].rawMaterialList = this.$deepClone(this.tableData1)
            this.processFlowList[this.currentProcessIndex].returnMaterialList = this.$deepClone(this.tableData2)
            console.log(this.processFlowList)
            const cacheData = this.$deepClone(this.formData)
            cacheData.processList = this.$deepClone(this.processFlowList)
            console.log(cacheData)
            addOrUpdate(cacheData).then(res => {
              this.$message({
                message: res.msg,
                type: 'success'
              })
              this.$layer.close(this.layerid) // 关闭弹框
              this.$parent.refresh() // 调用父组件的刷新方法
            })
          }
        }
      })
    },
    cancel() {
      this.$layer.close(this.layerid)// 关闭弹框
    },

    chooseMaterial() {
      this.triggerTag = true
      this.$layer.iframe({
        // 弹框
        content: {
          content: ChooseMaterial, // 传递的组件对象
          parent: this, // 当前的vue对象
          data: {
            selectedRow: this.formData
          }
        },
        area: ['1000px', '650px'],
        title: '选择物料', // 标题
        shadeClose: false // 点击遮罩是否关闭
      })
    },
    chooseMaterial2(e) {
      this.triggerTag = true
      this.$layer.iframe({
        // 弹框
        content: {
          content: ChooseMaterial2, // 传递的组件对象
          parent: this, // 当前的vue对象
          data: {
            selectedRow: e == 1 ? this.tableData1 : this.tableData2,
            way: e
          }
        },
        area: ['1000px', '650px'],
        title: '选择物料', // 标题
        shadeClose: false // 点击遮罩是否关闭
      })
    },
    chooseMaterialCallBack(row) {
      this.formData.materialId = row.materialId
      this.formData.materialCode = row.materialCode
      this.formData.materialName = row.materialName
      this.formData.materialModel = row.materialModel
      this.formData.materialTypeName = row.materialTypeName
      this.formData.materialUnitName = row.materialUnitName
      getProcessInfoByMaterialId(this.formData.materialId).then(res => {
        this.processFlowList = res.data
        this.processFlowList.forEach(ele => {
          ele.engineeringProcessName = ele.name
          ele.processId = ele.id
        })
        if (this.processFlowList) {
          this.initProcessFlowData()
        }
      })
    },
    chooseMaterialCallBack2(data) {
      // data.forEach(ele => {
      //   ele.materialCode = ele.materialCode
      //   ele.materialName = ele.materialName
      //   ele.materialModel = ele.materialModel
      //   ele.materialTypeName = ele.materialTypeName
      //   ele.materialUnitName = ele.materialUnitName
      // })
      this.tableData1 = data
    },
    chooseMaterialCallBack3(data) {
      // data.forEach(ele => {
      //   ele.materialCode = ele.materialCode
      //   ele.materialName = ele.materialName
      //   ele.materialModel = ele.materialModel
      //   ele.materialTypeName = ele.materialTypeName
      //   ele.materialUnitName = ele.materialUnitName
      // })
      this.tableData2 = data
    },
    initProcessFlowData() { // 初始化外协工序数据
      if (this.processFlowList.length > 0) {
        this.processFlowList.forEach(item => {
          item['returnMaterialList'] = []
          item['rawMaterialList'] = []
        })

        // 模拟点击第一条
        this.currentProcess = this.processFlowList[0]
        this.currentProcessIndex = 0
        this.tableData1 = this.currentProcess.rawMaterialList || []
        this.tableData2 = this.currentProcess.returnMaterialList || []
      }
    }
  }
}
</script>

<style lang="less" scoped>
.shows {
 padding-top: 10px !important;
  padding-bottom: 10px ;
}
.processRequirement_bottom{
  display: flex;
  border-top: 1px solid rgba(105,105,105,0.2);
  margin-top: 20px;
  .processRequirement_bottom_tree{
    width: 30%;
    border-right: 1px solid rgba(105,105,105,0.2);
    .tree_header{
      height: 50px;
      margin: 0 20px;
      display: flex;align-items: center;
      font-size: 14px;
      color: #333333;
      border-bottom: 1px solid #387BFC;
    }
    .tree_container{
      margin: 0 20px;overflow-y: overlay;

      .tree_container_item{
        height: 40px;display: flex;align-items: center;
        justify-content: space-between;
        padding-left:20px;
      }
      .selected_row{

        background-color: rgba(56,123,252,1);
        color: white;
      }

      .tree_container_item:hover{
        background-color: rgba(56,123,252,0.5);
        color: white;
      }
    }
  }
  .processRequirement_bottom_detail{
    width: 70%;
    .formItem_header_padding{
      margin-top: 20px;
    }
    .detail_form{
      display: flex;align-items: center;
      .detail_form_item{
        width: calc(50% - 40px);
        display: flex;align-items: center;
        margin-left: 20px;
        margin-right: 20px;
        .detail_form_item_name{
          height: 30px;
          line-height: 30px;
          width: 120px;
          font-size: 14px;
          color: #666;
        }
        .detail_form_item_input{
          width: calc(100% - 120px);
          /deep/ .el-input__inner{
            height: 30px;
            line-height: 30px;
          }
        }
      }
    }
  }
}
.addWorkProcedure{
  margin:10px 20px;
  height: 40px;
  line-height: 40px;
  text-align: center;
  border: 1px solid #999;
  color: #999;
  cursor: pointer;
}

/deep/ .el-form-item{
  .el-form-item__label{
    color: #1F51B3;
    font-size: 15px;
  }
  .el-form-item__content{
    color: #333333;
    font-size: 15px;
  }
}
.el-table {
  font-size: 15px;
}
.noData{
  color: #c0c4cc;
}
</style>
